<?php

/**
 * account actions.
 *
 * @package    blogallery
 * @subpackage account
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 2692 2006-11-15 21:03:55Z fabien $
 */
class accountActions extends sfActions
{  
  public function executeLogin()
  {
    if ($this->getUser()->isAuthenticated())
    {
      $this->redirect('@homepage');
    }
    
    if( $this->getRequest()->getMethod() == sfRequest::POST )
    {
      $user = UserPeer::retrieveByUsername($this->getRequestParameter('username'));
      
      if(!$user)
      {
        $this->getRequest()->setError('login', 'Entered credentials are wrong.');
      }
      elseif(sha1($user->getSalt().$this->getRequestParameter('password')) != $user->getPassword())
      {
        $this->getRequest()->setError('login', 'Entered credentials are wrong.');
      }
      else
      {	      
        $this->getUser()->signIn($user, $this->getRequestParameter('remember'));
        
        $this->redirect('@homepage');	
      }
    }

    return sfView::SUCCESS;
  }
  
  public function executeLogout()
  {
    $this->getUser()->signOut();
    $this->redirect('@homepage');
  }
  
  public function executeReset()
  {
    if($this->getUser()->isAuthenticated())
    {
      $this->redirect('@homepage');
    }
    
  	if ($this->getRequest()->getMethod() != sfRequest::POST)
  	{
  	  return sfView::INPUT;	
  	}
  	else
  	{
      $c = new Criteria();
      $c->add(UserPeer::EMAIL, $this->getRequestParameter('email'));
  	
      $user = UserPeer::doSelectOne($c);
  	
      if (!$user instanceof User)
      {
  	    $this->getRequest()->setError('user', 'Пользователя с таким адресом электронной почты не существует');
  	    return sfView::ERROR;
      }
      else
      {
      	// generate new password
        $password = myUserTools::makePassword();
        
        // set new password
        $user->setHashedPassword($password);
        $user->save();
        
        // send new password
        $this->setFlash('reset_email', $user->getEmail());
        $this->setFlash('reset_password', $password);
        $this->sendEmail('mail', 'reset');
        
        // log the email
        $this->logMessage($email, 'debug');
        $this->email = $email;        
        
        return sfView::SUCCESS;
      }      
  	}  	
  }
    
  public function handleErrorLogin()
  {
    return sfView::SUCCESS;
  }  
}
